# -*- coding: utf-8 -*-
# @Time    : 2024/10/15 20:16
# @Author  : cx
# @File    : websockets_kh.py
# @Software: PyCharm
import asyncio
import websockets

class WebSocketClient:
    sj = '{"ml": "a01", "xm": 3, "yhid": "cx02"}'
    ssj = '{"qing_qiu": 1,"code": "9C9E6EEBB078", "ma": "93352674dfaa450f81980801d9e72ed4"}'
    def __init__(self, uri):
        self.uri = uri
        self.websocket = None

    async def connect(self):
        # 连接到服务器并保存连接
        self.websocket = await websockets.connect(self.uri)

    async def send_heartbeat(self):
        # 持续发送心跳消息
        while True:
            await self.websocket.send(self.ssj)
            await asyncio.sleep(10)  # 每10秒发送一次心跳


    async def receive_messages(self):
        # 接收服务器消息
        while True:
            try:
                response = await self.websocket.recv()
                print(f"Received from server: {response}")
            except websockets.exceptions.ConnectionClosed:
                print("Connection closed")
                break

    async def run(self):
        await self.connect()

        # 运行心跳发送和消息接收任务
        heartbeat_task = asyncio.create_task(self.send_heartbeat())
        receive_task = asyncio.create_task(self.receive_messages())

        # 等待任务完成
        await heartbeat_task
        await receive_task

    async def close(self):
        # 关闭连接
        await self.websocket.close()

# 替换成你的WebSocket服务器地址和端口
uri = "ws://192.168.1.12:8080"

# 创建WebSocket客户端实例
client = WebSocketClient(uri)

# 运行客户端
asyncio.run(client.run())

# 如果需要，可以关闭连接
# asyncio.run(client.close())
